<template>
	<view class="box">
		<view class="top-cont"></view>
		<view>
			<scroll-view scroll-x class="bg-white nav text-center ">
				<view class="cu-item " :class="actIdx==0?'text-black cur':''" @click="actIdx=0">热门</view>
				<view class="cu-item " :class="actIdx==1?'text-black cur':''" @click="actIdx=1">发现</view>
				<view class="cu-item " :class="actIdx==2?'text-black cur':''" @click="actIdx=2">话题</view>
				<view class="cu-item " :class="actIdx==3?'text-black cur':''" @click="actIdx=3">言物</view>
				<view class="cuIcon-search text-xl "></view>
			</scroll-view>
		</view>

	</view>

	<!-- 热门 -->
	<view class="" v-if="actIdx==0">
		<view class="bg-gray padding-top padding-left-xl text-lg">
			可能感兴趣的
		</view>
		<scroll-view scroll-x class="bg-gray scroll-int">
			<view class="">
				<view class="flex">
					<custom-interest v-for="item in interest" :key="item.objectId" :data="item"></custom-interest>
				</view>
			</view>
		</scroll-view>
		<custom-card v-for="item in hot" :key="item.objectId" :data="item"
			@update="(field:fieldType, value:number) => handleActionUpdate(field, value, item.objectId!)"></custom-card>
	</view>


	<!-- 发现页 -->
	<view v-if="actIdx === 1">
		<!-- 分类导航 -->
		<scroll-view scroll-x class="bg-white nav text-center">
			<view class="cu-item" :class="actIndex === item.id ? 'text-black text-bold' : ''"
				@click="actIndex = item.id" v-for="item in discoverCategories" :key="item.id">
				{{ item.label }}
			</view>
		</scroll-view>

		<!-- 当前分类数据 -->
		<view>
			<custom-card v-for="item in contData[actIndex]" :key="item.objectId" :data="item"
				@update="(field:fieldType, value:number) => handleActionUpdate(field, value, item.objectId!)"></custom-card>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, ref, type Ref } from 'vue';
	import type { Post } from '@/model/goods';
	import http from '@/utils/http';
	import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
	import { goodUpdate } from '@/api/createGoods_api';

	const actIdx : Ref<number> = ref(0)
	const actIndex : Ref<number> = ref(0)
	const page = ref(1); // 当前页码（从 1 开始）

	// 1. 分类配置
	const discoverCategories = [
		{ id: 0, label: '所有', where: {} },
		{ id: 1, label: '原创', where: { isOriginal: true } },
		{ id: 2, label: '文字', where: { category: '文字' } },
		{ id: 3, label: '诗', where: { category: '诗' } },
		{ id: 4, label: '电影', where: { category: '电影' } },
		{ id: 5, label: '语录', where: { category: '语录' } },
		{ id: 6, label: '歌词', where: { category: '歌词' } },
	];

	// 2. 存储所有分类数据
	const contData = ref<Record<number, Post[]>>({});

	// 3. 初始化数据
	const initDiscoverData = async () => {
		try {
			//for...of 循环遍历数组中的每个元素
			for (const category of discoverCategories) {
				const res = await http.get('/classes/goods', {
					params: {
						where: category.where,
						order: '-createdAt'
					}
				});
				contData.value[category.id] = res.data.results;//“所有” 分类（id: 0）的数据
			}
		} catch (err) {
			console.error('发现页数据加载失败', err);
			uni.showToast({ title: '数据加载失败', icon: 'none' });
		}
	};
	onMounted(() => {
		initDiscoverData();
	});



	// 4. 互动更新处理
	type fieldType = 'favorites' | 'comments' | 'likes'
	const handleActionUpdate = async (
		field : 'favorites' | 'comments' | 'likes',
		newValue : number,
		objectId : string
	) => {
		try {
			const goodData = { [field]: newValue }
			await goodUpdate(objectId, goodData)
			Object.values(contData.value).forEach(categoryPosts => {
				const target = categoryPosts.find(item => item.objectId === objectId);
				if (target) {
					target[field] = newValue; // 更新本地字段，触发视图刷新
				}
			});
			const hotTarget = hot.value.find(item => item.objectId === objectId);
			if (hotTarget) {
				hotTarget[field] = newValue;
			}

			// 提示成功
			uni.showToast({ title: '操作成功', icon: 'none' });
		} catch (err) {
			console.error(`更新${field}失败`, err);
			uni.showToast({ title: '操作失败', icon: 'none' });
		}
	};


	// 热门列表渲染
	const hot = ref<Array<Post>>([])
	http.get('/classes/goods').then(res => {
		let { results } = res.data
		page.value = 1;
		hot.value = results.filter(() => {
			return Math.random() > 0.5
		})
	})

	// 兴趣横渲染
	const interest = ref<Array<Post>>([])
	http.get('/classes/goods').then(res => {
		let { results } = res.data
		interest.value = results.filter(() => {
			return Math.random() > 0.5  //随机筛选
		})
	})


	// 下拉刷新
	onPullDownRefresh(() => {
		console.log('下拉刷新');
		try {
			http.get('/classes/goods', {
				params: {
					limit: 6,
					skip: 0,
					order: '-createdAt'
				}
			}).then(res => {
				hot.value = res.data.results
				page.value = 1; // 重置页码
				uni.stopPullDownRefresh() //主动关闭刷新动画
			})
			http.get('/classes/goods').then(res => {
				let { results } = res.data
				interest.value = results.filter(() => {
					return Math.random() > 0.5  //随机筛选
				})
			})
		} catch (err) {
			uni.showToast({
				title: '刷新失败',
				icon: 'none'
			})
		}
		uni.showToast({
			title: '刷新成功',
			icon: 'none'
		})

	})

	// 触底分页
	onReachBottom(() => {
		console.log('触底了');
		let skip = page.value * 6
		http.get('/classes/goods', {
			params: {
				limit: 6,
				skip,
				order: '-createdAt'
			}
		}).then(res => {

			let results = res.data.results
			if (results.length != 0) {
				hot.value = [
					...hot.value,
					...results
				]
				page.value++
				return
			}
			uni.showToast({
				icon: 'none',
				title: '没有更多数据了'
			})

		})
	})
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.box {
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.top-cont {
		height: 60upx;
		background-color: #FFFFFF;
	}

	.scroll-int {
		padding: 0 0upx 26upx 26upx;
	}

	.cur {
		border-bottom: 4rpx solid blue !important;
		padding: 0 0upx !important;
		margin: 0 30upx !important;
		font-weight: 550;
	}

	.cuIcon-search {
		position: absolute;
		top: 25upx;
		right: 30upx;

	}
</style>